App.User = angular.module('User', ['Api']).
controller('User.Ctrl', ['$scope', function ($scope) {

}]).
service('User.ConfigService', ['MainApp.ConfigService', function (Config) {
	this.directiveDir = Config.Template.templateDir+'User/';
}]).
factory('User.Factory', ['Api.Service', 'MainApp.ConfigService', 'Error.Service', '$q', 'Note.Factory', function (Api, Config, Error, $q, Note) {
	function User () {
		var that = this,
			login,
			password,
			notes;
		function setLogin (nLogin) {
			login = nLogin;
		}
		function setPassword (nPassword) {
			password = nPassword;
		}
		function getLogin () {
			return login;
		}
		function getPassword () {
			return password;
		}
		function addNote (note) {
			notes.addNote(note);
		}
		function downloadData () {
			var d = $q.defer();
			Note.getUserNotes(this).then(
				function (notesGroup) {
					notes = notesGroup;
					d.resolve(true);
				},
				function (error) {
					d.reject(error);
				}
			);
			return d.promise;
		}
		function getNotes () {
			return notes;
		}
		function toObject () {
			return {
				login: login,
				password: password,
				notes: notes.toObject()
			}
		}
		(function construct () {
			that.setLogin = setLogin;
			that.setPassword = setPassword;
			that.getLogin = getLogin;
			that.getPassword = getPassword;
			that.toObject = toObject;
			that.downloadData = downloadData;
			that.addNote = addNote;
			that.getNotes = getNotes;
		})();
	}
	User.fromObject = function (obj) {
		var nUser = new User();
		nUser.setLogin(obj.login);
		nUser.setPassword(obj.password);
		return nUser;
	}
	User.checkUser = function (login, password) {
		var mems = Api.GetMems.fromObject({
				user: login,
				pass: password
			}),
			d = $q.defer();
		Api.getData(mems, function (response) {
			if(response == false) {
				d.reject(new Error.BaseError());
			} else {
				if(response.rez == Config.Api.validResponseValue) {
					d.resolve(true);
				} else {
					d.reject(Error.BadLoginDataError());
				}
			}
		});
		return d.promise;
	}
	User.login = function (login, password) {
		var d = $q.defer();
		User.checkUser(login, password).then(
			function (user) {
				d.resolve(User.fromObject({
					login: login,
					password: password
				}));
			},
			function (error) {
				d.reject(error);
			}
		);
		return d.promise;
	}
	return User;
}]).
directive('userLoginForm', ['User.ConfigService', 'MainApp.ConfigService', 'User.Factory', '$rootScope', function (UserConfig, Config, User, $rootScope) {
	var url = UserConfig.directiveDir+'loginForm'+Config.Template.directiveExt;
	return {
		restrict: 'E',
		templateUrl: url,
		replace: true,
		controller: function ($scope) {
			$scope.user = '';
			$scope.password = '';
			$scope.login = function () {
				User.login($scope.user, $scope.password).then(
					function (user) {
						$rootScope.$broadcast('User.login', user);
					},
					function (error) {
						$rootScope.$broadcast('Error.catch', error);
					}
				);
			}
		}
	}
}]);